from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from sqlalchemy import desc
from typing import List, Optional
from datetime import datetime
from backend.database import SessionLocal
from backend.models import JobSeekerProfile, User, UserType
from backend.schemas import JobSeekerProfileCreate, JobSeekerProfileResponse, JobSeekerProfileBase
import logging

# 设置日志记录
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 保持前缀空字符串
router = APIRouter(prefix="")

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

# 获取求职者简历列表
@router.get("/api/job-seeker-profiles", response_model=List[JobSeekerProfileResponse])
async def get_job_seeker_profiles(
    user_id: Optional[int] = Query(None),
    db: Session = Depends(get_db)
):
    """
    获取求职者简历列表。可以通过user_id筛选特定用户的简历
    """
    logger.info(f"请求获取简历列表: user_id={user_id}")
    try:
        query = db.query(JobSeekerProfile)
        
        # 如果指定了用户ID，则仅返回该用户的简历
        if user_id is not None:
            query = query.filter(JobSeekerProfile.user_id == user_id)
        
        # 按更新时间降序排序
        profiles = query.order_by(desc(JobSeekerProfile.last_updated)).all()
        logger.info(f"成功获取简历列表，找到{len(profiles)}份简历")
        return profiles
    except Exception as e:
        logger.error(f"获取简历列表失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取简历列表失败: {str(e)}")

# 获取简历详情
@router.get("/api/job-seeker-profiles/{profile_id}", response_model=JobSeekerProfileResponse)
async def get_job_seeker_profile(profile_id: int, db: Session = Depends(get_db)):
    """
    获取特定简历的详情
    """
    logger.info(f"请求获取简历详情: profile_id={profile_id}")
    profile = db.query(JobSeekerProfile).filter(JobSeekerProfile.profile_id == profile_id).first()
    if not profile:
        logger.warning(f"简历不存在: profile_id={profile_id}")
        raise HTTPException(status_code=404, detail="简历不存在")
    logger.info(f"成功获取简历详情: profile_id={profile_id}")
    return profile

# 创建新简历
@router.post("/api/job-seeker-profiles", response_model=JobSeekerProfileResponse)
async def create_job_seeker_profile(profile: JobSeekerProfileBase, db: Session = Depends(get_db)):
    """
    创建新的求职者简历
    """
    logger.info(f"请求创建新简历: user_id={profile.user_id}")
    # 验证用户存在
    user = db.query(User).filter(User.user_id == profile.user_id).first()
    if not user:
        logger.warning(f"用户不存在: user_id={profile.user_id}")
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 检查用户是否已有简历
    existing_profile = db.query(JobSeekerProfile).filter(JobSeekerProfile.user_id == profile.user_id).first()
    if existing_profile:
        logger.warning(f"用户已有简历: user_id={profile.user_id}")
        raise HTTPException(status_code=400, detail="用户已有简历，请使用更新接口")
    
    # 创建新简历
    db_profile = JobSeekerProfile(
        user_id=profile.user_id,
        desired_position=profile.desired_position,
        current_status=profile.current_status,
        experience_years=profile.experience_years,
        expected_salary=profile.expected_salary,
        education_level=profile.education_level,
        skills=profile.skills,
        last_updated=datetime.utcnow()
    )
    
    db.add(db_profile)
    db.commit()
    db.refresh(db_profile)
    logger.info(f"成功创建新简历: profile_id={db_profile.profile_id}")
    return db_profile

# 更新简历
@router.put("/api/job-seeker-profiles/{profile_id}", response_model=JobSeekerProfileResponse)
async def update_job_seeker_profile(profile_id: int, profile_update: JobSeekerProfileBase, db: Session = Depends(get_db)):
    """
    更新现有简历信息
    """
    # 查找简历
    db_profile = db.query(JobSeekerProfile).filter(JobSeekerProfile.profile_id == profile_id).first()
    if not db_profile:
        raise HTTPException(status_code=404, detail="简历不存在")
    
    # 验证权限 (只有简历所有者才能更新)
    if db_profile.user_id != profile_update.user_id:
        raise HTTPException(status_code=403, detail="无权限修改此简历")
    
    # 更新简历信息
    update_data = profile_update.dict(exclude_unset=True)
    
    for key, value in update_data.items():
        setattr(db_profile, key, value)
    
    # 更新last_updated字段
    db_profile.last_updated = datetime.utcnow()
    
    db.commit()
    db.refresh(db_profile)
    return db_profile

# 删除简历
@router.delete("/api/job-seeker-profiles/{profile_id}")
async def delete_job_seeker_profile(profile_id: int, user_id: int = Query(...), db: Session = Depends(get_db)):
    """
    删除简历
    """
    # 查找简历
    db_profile = db.query(JobSeekerProfile).filter(JobSeekerProfile.profile_id == profile_id).first()
    if not db_profile:
        raise HTTPException(status_code=404, detail="简历不存在")
    
    # 验证权限 (简历所有者或管理员才能删除)
    user = db.query(User).filter(User.user_id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    if db_profile.user_id != user_id and user.user_type != UserType.admin:
        raise HTTPException(status_code=403, detail="无权限删除此简历")
    
    # 删除简历
    db.delete(db_profile)
    db.commit()
    
    return {"message": "简历已删除"} 